<template>
  <div>
    <el-dialog v-model="dialogVisible" width="80%" align-center :close-on-click-modal="false" :show-close="false"
      :before-close="handleClose" destroy-on-close draggable>
      <template #header="{ close }">
        <div class="dialog-header flex justify-between items-center">
          <div>申报计划{{ ruleForm.id ? '编辑' : '新增' }}</div>
          <el-icon class="el-icon--left cursor-pointer" @click="close">
            <CircleCloseFilled color="#fff" />
          </el-icon>
        </div>
      </template>
      <el-form :model="ruleForm" :rules="rules" label-width="130px" ref="ruleFormRef">
        <!-- 基本信息 -->
        <div class="bg-white mt-[10px]">
          <BaseHead>基本信息</BaseHead>
          <div class="p-[10px]">

            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="申报计划名称" prop="name">
                  <el-input placeholder="请输入申报计划名称" v-model="ruleForm.name" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="奖励名称" prop="honorName">
                  <el-input placeholder="请输入奖励名称" v-model="ruleForm.honorName" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="奖励级别" prop="honorLevel">
                  <el-select v-model="ruleForm.honorLevel" placeholder="请选择获奖级别" clearable>
                    <el-option v-for="item in hjjbList" :key="item.code" :label="item.name" :value="item.code" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="申报开始日期">
                  <el-date-picker v-model="ruleForm.beginDate" type="date" format="YYYY/MM/DD" value-format="YYYY-MM-DD"
                    :disabled-date="disableAfterEndDate" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="申报结束日期">
                  <el-date-picker v-model="ruleForm.endDate" type="date" format="YYYY/MM/DD" value-format="YYYY-MM-DD"
                    :disabled-date="disableBeforeStartDate" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="可转入评审">
                  <el-radio-group v-model="ruleForm.isReview">
                    <el-radio value="1" size="large">是</el-radio>
                    <el-radio value="0" size="large">否</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="自动截止" prop="isAutoEnd">
                  <el-radio-group v-model="ruleForm.isAutoEnd">
                    <el-radio value="1" size="large">是</el-radio>
                    <el-radio value="0" size="large">否</el-radio>
                  </el-radio-group>
                  <div style="margin-left: 16px;"> 申请结束日期当日24时自动停止申报</div>
                </el-form-item>
              </el-col>

              <el-col :span="24">
                <el-form-item label="备注">
                  <el-input v-model="ruleForm.note" type="textarea" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="申报指南">
                  <FileUpload :uploadUrl="uploadUrl" :limit="3" tip="最多可上传3个附件,每个附件大小不超过20M" v-model="fileList"
                    @change="fileChange">
                  </FileUpload>
                </el-form-item>
              </el-col>

            </el-row>

          </div>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <div class="operate-btns">
            <el-button type="primary" @click="submitForm(ruleFormRef)" :loading="btnLoading">保存</el-button>
            <el-button type="primary" @click="closeMet">关闭</el-button>
          </div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import BaseHead from "@/views/project/components/BaseHead.vue";
import { honorApplyAdd, gethonorApplyUpdate } from "@/api/achievement/cghj"
import { ElMessage, ElMessageBox } from "element-plus";
import FileUpload from "@/views/achievement/components/FileUpload.vue"
const dialogVisible = defineModel();
const props = defineProps({
  hjjbList: Array,
})
const ruleForm = reactive({
  name: '',
  honorName: '',
  honorLevel: '',
  isReview: '',
  isAutoEnd: '',
  beginDate: '',
  endDate: '',
  note: '',
  fileId: '',
  applyState: '0',
})
const rules = reactive({
  name: [
    { required: true, message: '请输入申报计划名称', trigger: 'blur' },
  ],
  honorName: [
    { required: true, message: '请输入奖励名称', trigger: 'blur' },
  ],
  honorLevel: [
    {
      required: true,
      message: '请选择奖励级别',
      trigger: 'change',
    },
  ],
  isAutoEnd: [
    {
      required: true,
      message: '请选择自动截止',
      trigger: 'change',
    },
  ],

})

const btnLoading = ref(false)
const ruleFormRef = ref()
const submitForm = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('submit!')
      let params = {
        ...ruleForm,
      }
      console.log(params, 'params')
      btnLoading.value = true;
      if (params.id) {
        gethonorApplyUpdate(params).then((res) => {
          if (res.code == 200) {
            ElMessage({
              message: res.msg,
              type: 'success',
            })
            dialogVisible.value = false
            initData()
            emit('callBack', "1")
          } else {
            ElMessage({
              message: res.msg,
              type: 'error',
            })
          }
          btnLoading.value = false;
        })
      } else {
        honorApplyAdd(params).then((res) => {
          if (res.code == 200) {
            ElMessage({
              message: res.msg,
              type: 'success',
            })
            dialogVisible.value = false
            initData()
            emit('callBack', "1")
          } else {
            ElMessage({
              message: res.msg,
              type: 'error',
            })
          }
          btnLoading.value = false;
        })
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}

const emit = defineEmits(['callBack']);
const uploadUrl = `/commonFile/uploadFile?modelName=honorApplyApply`;
const fileList = ref([]);
const handleClose = (done) => {
  Object.assign(ruleForm, {
    name: '',
    honorName: '',
    honorLevel: '',
    isReview: '',
    isAutoEnd: '',
    beginDate: '',
    endDate: '',
    note: '',
    fileId: '',
    applyState: '0',
  })
  delete ruleForm.id;
  fileList.value = []
  emit('callBack', "")
  done()
}
const initData = () => {
  Object.assign(ruleForm, {
    name: '',
    honorName: '',
    honorLevel: '',
    isReview: '',
    isAutoEnd: '',
    beginDate: '',
    endDate: '',
    note: '',
    fileId: '',
    applyState: '0',
  })
  delete ruleForm.id;
  fileList.value = []
}

const closeMet = () => {
  initData()
  dialogVisible.value = false
}

const getRuleForm = (i) => {
  for (const key in i) {
    ruleForm[key] = i[key];
  }
  if (i.fileList && i.fileList.length > 0) {
    fileList.value = i.fileList.map((item) => {
      return {
        name: item.fileName,
        id: item.id,
      };
    });
  }
  console.log(ruleForm, 'ruleForm')
}
//上传的文件改变
const fileChange = () => {
  const ids = fileList.value.map((item) => {
    const id = item.response ? item.response.data : item.id;
    return id;
  });
  ruleForm.fileId = ids.join(",");
};
defineExpose({
  getRuleForm
})

const disableBeforeStartDate = (time) => {
  if (!ruleForm.beginDate) return false; // 如果没有开始日期，则不限制结束日期
  return time.getTime() <= new Date(ruleForm.beginDate).getTime(); // 禁用所有在开始日期之前的日期
}

const disableAfterEndDate = (time) => {
  if (!ruleForm.endDate) return false; // 如果没有开始日期，则不限制结束日期
  return time.getTime() >= new Date(ruleForm.endDate).getTime(); // 禁用所有在开始日期之前的日期
}

</script>

<style scoped lang="scss">
@import url("@/views/achievement/index.scss");
</style>
